"""
计算器插件示例
"""
from datetime import datetime
from typing import Dict, Any, List
from fastapi import APIRouter
from pydantic import BaseModel

from plugin_system.base import BasePlugin, PluginInfo, PluginConfig


class CalculationRequest(BaseModel):
    """计算请求模型"""
    operation: str
    a: float
    b: float


class CalculatorPlugin(BasePlugin):
    """计算器插件"""
    
    def __init__(self):
        super().__init__()
        self.router = APIRouter(prefix="/calculator", tags=["calculator"])
        self._setup_routes()
    
    def get_info(self) -> PluginInfo:
        """获取插件信息"""
        return PluginInfo(
            name="calculator",
            version="1.0.0",
            description="一个简单的计算器插件，支持基本数学运算",
            author="FastAPI Plugin System",
            homepage="https://github.com/fastapi-plugins",
            dependencies=[],
            tags=["utility", "calculator", "math"],
            created_at=datetime.now(),
            updated_at=datetime.now()
        )
    
    def initialize(self) -> bool:
        """初始化插件"""
        try:
            self.info = self.get_info()
            self.config = PluginConfig(
                enabled=True,
                settings={
                    "precision": 2,
                    "allowed_operations": ["add", "subtract", "multiply", "divide"]
                },
                auto_start=False
            )
            return True
        except Exception as e:
            print(f"计算器插件初始化失败: {e}")
            return False
    
    def start(self) -> bool:
        """启动插件"""
        try:
            print("计算器插件已启动")
            return True
        except Exception as e:
            print(f"计算器插件启动失败: {e}")
            return False
    
    def stop(self) -> bool:
        """停止插件"""
        try:
            print("计算器插件已停止")
            return True
        except Exception as e:
            print(f"计算器插件停止失败: {e}")
            return False
    
    def get_routes(self) -> List[Dict[str, Any]]:
        """获取插件路由"""
        return [
            {
                "path": "/calculator/add",
                "methods": ["POST"],
                "description": "加法运算"
            },
            {
                "path": "/calculator/subtract",
                "methods": ["POST"],
                "description": "减法运算"
            },
            {
                "path": "/calculator/multiply",
                "methods": ["POST"],
                "description": "乘法运算"
            },
            {
                "path": "/calculator/divide",
                "methods": ["POST"],
                "description": "除法运算"
            },
            {
                "path": "/calculator/calculate",
                "methods": ["POST"],
                "description": "通用计算接口"
            }
        ]
    
    def _setup_routes(self):
        """设置路由"""
        
        @self.router.post("/add")
        async def add(request: CalculationRequest):
            """加法运算"""
            result = request.a + request.b
            precision = self.config.settings.get("precision", 2)
            return {
                "operation": "add",
                "a": request.a,
                "b": request.b,
                "result": round(result, precision),
                "plugin": self.info.name
            }
        
        @self.router.post("/subtract")
        async def subtract(request: CalculationRequest):
            """减法运算"""
            result = request.a - request.b
            precision = self.config.settings.get("precision", 2)
            return {
                "operation": "subtract",
                "a": request.a,
                "b": request.b,
                "result": round(result, precision),
                "plugin": self.info.name
            }
        
        @self.router.post("/multiply")
        async def multiply(request: CalculationRequest):
            """乘法运算"""
            result = request.a * request.b
            precision = self.config.settings.get("precision", 2)
            return {
                "operation": "multiply",
                "a": request.a,
                "b": request.b,
                "result": round(result, precision),
                "plugin": self.info.name
            }
        
        @self.router.post("/divide")
        async def divide(request: CalculationRequest):
            """除法运算"""
            if request.b == 0:
                return {"error": "除数不能为零"}
            
            result = request.a / request.b
            precision = self.config.settings.get("precision", 2)
            return {
                "operation": "divide",
                "a": request.a,
                "b": request.b,
                "result": round(result, precision),
                "plugin": self.info.name
            }
        
        @self.router.post("/calculate")
        async def calculate(request: CalculationRequest):
            """通用计算接口"""
            allowed_operations = self.config.settings.get("allowed_operations", [])
            
            if request.operation not in allowed_operations:
                return {"error": f"不支持的操作: {request.operation}"}
            
            operations = {
                "add": lambda a, b: a + b,
                "subtract": lambda a, b: a - b,
                "multiply": lambda a, b: a * b,
                "divide": lambda a, b: a / b if b != 0 else None
            }
            
            if request.operation == "divide" and request.b == 0:
                return {"error": "除数不能为零"}
            
            result = operations[request.operation](request.a, request.b)
            precision = self.config.settings.get("precision", 2)
            
            return {
                "operation": request.operation,
                "a": request.a,
                "b": request.b,
                "result": round(result, precision),
                "plugin": self.info.name
            } 